package com.caojing.androidviewpage

import android.animation.ValueAnimator
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LayoutAnimationController
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2


class MainActivity : AppCompatActivity() {

    var viewPage: ViewPager2? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        viewPage = findViewById<ViewPager2>(R.id.viewPage)


        viewPage?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                // 获取当前页的视图并更新高度
                updateViewPagerHeight(viewPage, position)


            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                Log.d("滑动监听", "positionOffset:$positionOffset\npositionOffsetPixels:$positionOffsetPixels")
            }

        })

        viewPage?.adapter = CustomAdapter()
    }

    private fun updateViewPagerHeight(viewPage: ViewPager2?, position: Int) {
        val recyclerView = viewPage?.getChildAt(0) as RecyclerView
        val currentView = recyclerView.layoutManager?.findViewByPosition(position)
        currentView?.post {
            // 测量当前页高度
            currentView.measure(
                View.MeasureSpec.makeMeasureSpec(viewPage.width, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            )
            val measuredHeight = currentView.measuredHeight
            // 更新 ViewPager2 高度
            animateHeight(viewPage,measuredHeight)

//            viewPage.layoutParams = viewPage.layoutParams.apply {
//                height = measuredHeight
//            }

        }
    }

    private fun animateHeight(view: View, targetHeight: Int) {
        ValueAnimator.ofInt(view.height, targetHeight).apply {
            addUpdateListener { animator ->
                val layoutParams = view.layoutParams
                layoutParams.height = animator.animatedValue as Int
                view.layoutParams = layoutParams
            }
            duration = 300
            interpolator = AccelerateDecelerateInterpolator()
            start()
        }
    }


}